﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetCore.Ado;
using NetCore.Authorization;
using NetCore.Model;
namespace NetCore.BLL
{
    public class PageService : SerivceBase, IPageService
    {
        #region 属性
        public const string Page_No_Rule = "0002";
        #endregion
        #region 基本方法
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<PageEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(PageEntity.__IsDeleted, false);
            return this.Query<PageEntity>(criter).ToList();

        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public PageEntity GetById(object id)
        {
            return this.GetById<PageEntity>(id);

        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Save(PageEntity entity, ref string strError)
        {
            if (ChkPageName(entity.PageId, entity.LocalName, entity.ParentId))
            {
                strError = "页面存在，请检查";
                return false;
            }
            if (string.IsNullOrWhiteSpace(entity.PageId))
            {
                entity.PageId = new SerialRuleService().CreateSerialNo(Page_No_Rule, null, ref strError);
            }
            return this.SaveOrUpdate(entity);

        }
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
                return this.Delete<PageEntity>(deleteKey);
            }
            return true;
        }
        public LigerGrid ForGrid(LigerGrid ligerGrid)
        {
            ICriterion criter = Expression.Eq(PageEntity.__IsDeleted, false);
            string localName = ligerGrid.GetValue(PageEntity.__LocalName);
            string routeUrl = ligerGrid.GetValue(PageEntity.__RouteUrl);
            if (!string.IsNullOrWhiteSpace(localName))
            {
                criter = Expression.And(Expression.Like(PageEntity.__LocalName, localName), criter);
            }
            if (!string.IsNullOrWhiteSpace(routeUrl))
            {
                criter = Expression.And(Expression.Like(PageEntity.__RouteUrl, routeUrl), criter);
            }
            return this.Query<PageEntity>(ligerGrid, criter);
        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 判断页面是否不存在
        /// </summary>
        /// <param name="UserId">用户id</param>
        /// <param name="userAccount">用户账户</param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool ChkPageName(string pageId, string pageName,string parentId)
        {
            ICriterion criter = Expression.And(
            Expression.Not(Expression.Eq(PageEntity._PrimaryKeyName, pageId)),
            Expression.And(Expression.Eq(PageEntity.__ActionName, pageName),
              Expression.And(Expression.Eq(PageEntity.__ParentId, parentId),
             Expression.Eq(PageEntity.__IsDeleted, false)))
             );
            var entity = this.Query<PageEntity>(criter).FirstOrDefault();
            return entity != null;
        }
        public List<PageEntity> GetMenuTree()
        {
            var lstAll = this.GetAll();
            var lstMenu = new List<PageEntity>();
            if (lstAll != null && lstAll.Count > 0)
            {
                foreach (var item in lstAll.Where(x=>string.IsNullOrWhiteSpace(x.ParentId)))
                {
                    lstMenu.Add(item);
                    GetChildTree(lstAll,item.PageId,"--",ref lstMenu);
                }
            }
            return lstMenu;
        }

        public void GetChildTree(List<PageEntity> lstAll,string parentid,string path,ref List<PageEntity> lstMenu)
        {
           
            if (lstAll != null && lstAll.Count > 0)
            {
               
                foreach (var item in lstAll.Where(x => x.ParentId == parentid))
                {
                    item.LocalName = path + item.LocalName;
                    lstMenu.Add(item);
                    GetChildTree(lstAll, item.PageId, path+ "--", ref lstMenu);
                }
            }
          
        }
        public List<BasePermissionAttribute> authAttributes;
        public List<PageEntity> GetChildTree(List<PageEntity> lstAll, string parentid)
        {
           // PageActionService pageActionService = new PageActionService();
            List<PageEntity> lstMenu = new List<PageEntity>();
            if (authAttributes == null)
            {
                authAttributes = ControllerHelper.AuthAttributes;
            }
            if (lstAll != null && lstAll.Count > 0)
            {
                lstMenu = lstAll.Where(x => x.ParentId == parentid).ToList();
                foreach (var item in lstMenu)
                {
                    item.LstActions = new List<BasePermissionAttribute>();
                    string areaname = "";
                    string controllerName = "";
                    string actionName = "";
                    if (item.RouteUrl.IndexOf("/") == 0)
                    {
                        item.RouteUrl = item.RouteUrl.Substring(1);
                    }
                    string[] array = item.RouteUrl.Split('/');
                    areaname = array[0].ToLower();
                    if (array.Length >= 3)
                    {
                        controllerName = array[1].ToLower();
                        actionName = array[2].ToLower();
                    }
                    else if(array.Length >= 2)
                    {
                        controllerName = array[1].ToLower();
                    }
                    item.LstActions = authAttributes.Where(x => x.AreaName.ToLower().Equals(areaname) && x.ControllerName.ToLower().Equals(controllerName) ).ToList();
                    //if (actions != null && actions.Count > 0)
                    //{
                    //    foreach (var action in actions)
                    //    {
                    //        item.LstActions.Add(new PageActionEntity {
                    //             ActionId=action.ActionCode,
                    //             ActionName=action.ActionName,
                    //             PageActionId=item.PageId+"_"+action.ActionCode,
                    //            LocalName=action.Description
                    //        });
                    //    }
                    //}
                    //item.LstActions = pageActionService.ForGrid(item.PageId, "", "");
                }
            }
            return lstMenu;

        }
        #endregion

    }
}